package pl.nith.battleships.net;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


public class Server extends Thread
{
	private ServerSocket	listener		= null;
	private boolean			listening		= true;

	public static final int	LISTENING_PORT	= 4444;
	public boolean			isServerRunning	= false;
	
	private HashMap<String, ConnectionHandler> clientList;

	public Server()
	{
		clientList = new HashMap<String, ConnectionHandler>();
	}
	
	@SuppressWarnings("unchecked")
	public void sendMessage(String receiver, String message)
	{
		Iterator<?> it = clientList.entrySet().iterator();
		
		while (it.hasNext())
		{
			Map.Entry<String, ConnectionHandler> entry = (Entry<String, ConnectionHandler>) it.next();
			
			if (entry.getKey().equals(receiver))
				entry.getValue().SendMessage(message);
		}
		
	}

	public void run()
	{
		try
		{
			listener = new ServerSocket(LISTENING_PORT);
		}
		catch (IOException e)
		{
			System.err.println("Could not listen on port: " + LISTENING_PORT);
			System.exit(-1);
		}

		while (listening)
		{
			try
			{
				ConnectionHandler client = new ConnectionHandler(listener.accept());
				clientList.put("ID1", client);
				client.start();
			}
			catch (IOException e)
			{
				System.err.println("Could not start new thread.");
				System.exit(-1);
			}
		}
	}
}
